'use strict';
// import process from 'process'

module.exports = core;

const path = require('path')
const semver = require('semver')
const colors = require('colors/safe')
const os = require('os');
const userHome = require('user-home');
const pathExists = require('path-exists').sync;

const pkg = require('../package.json')
const log = require('@lcf-cli-dev/log')
const constant = require('./const');

function core() {
    try {
        checkPkgVersion()
        checkNodeVersion()
        checkRoot()
        checkUserHome()
        checkIputArgs()
        checkEnv()
        checkGlobalUpdate()
    } catch (e) {
        log.error(e.message)
    }
}

async function checkGlobalUpdate () {
    const currentVersion = pkg.version
    const npmName = pkg.name
    const {getNpmSemverVersion} = require('@lcf-cli-dev/get-npm-info')
    const lastVersion = await getNpmSemverVersion(currentVersion, npmName)
    if (lastVersion && semver.gt(lastVersion, currentVersion)) {
        log.warn(colors.yellow('更新提示', `请手动更新 ${npmName}， 当前版本${currentVersion}， 最新版本${lastVersion}`))
    }
}


function checkEnv () {
    const dotenv = require('dotenv')
    const dotenvPath = path.resolve(userHome, '.env')
    if (pathExists(dotenvPath)) {
        dotenv.config({
            path: dotenvPath
        })
    }
    createDefaultConfig()
    log.verbose('环境变量', process.env.CLI_HOME_PATH)
}
function createDefaultConfig () {
    const cliConfig = {
        home: 'userHome'
    }
    cliConfig['cliName'] = path.join(userHome, process.env.CLI_HOME || constant.DEFAULT_CLI_HOME)
    process.env.CLI_HOME_PATH = cliConfig.cliName
}


let args
function checkIputArgs () {
    const minimist = require('minimist')
    args = minimist(process.argv.slice(2))
    checkArgs()
}
function checkArgs () {
    if (args.debug) {
        process.env.LOG_LEVEL = 'verbose'
    } else {
        process.env.LOG_LEVEL = 'info'
    }
    log.level = process.env.LOG_LEVEL
}

function checkRoot () {
    const rootCheck = require('root-check')
    rootCheck()
    // console.log(os.userInfo()); // windows
    // console.log(process.geteuid); // macos
}

function checkUserHome () {
    if (!userHome || !pathExists(userHome)) {
        throw new Error(colors.red('当前用户主目录不存在'))
    }
}

function checkNodeVersion () {
    const lowest = constant.LOWEST_NODE_VERSION
    const current = process.version
    if (!semver.gte(current, lowest)) {
        throw new Error(colors.red(`clf-cli 需要安装 v${lowest} 版本以上的 node`))
    }
}

function checkPkgVersion () {
    log.notice('cli', pkg.version)
}